<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax</title>
</head>
<body>

<h1>the ajax-03 page</h1>
<button onclick="doAjaxGet()">do ajax get</button>
<button onclick="doAjaxPost()">do ajax post</button>
<button onclick="doAjaxDelete()">do ajax delete</button>
<button onclick="doAjaxUpdate()">do ajax update</button>
<div id="result">
    data is loading
</div>
<script src="/js/ajax.js"></script>
<script>

    function doAjaxGet() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("result").innerHTML = xhr.responseText;
            }
        }
        xhr.open("GET", "http://localhost/doAjaxGet", true);
        xhr.send(null);
    }

    function doAjaxPost() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("result").innerHTML = xhr.responseText;
            }
        }
        xhr.open("POST", "http://localhost/doAjaxPost", true);
        /* post请求需要设置请求头 必须在open之后 */
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        /* send里面写参数数据 */
        xhr.send("id=2&name=电脑&remark=游戏本");
    }

    function doAjaxDelete() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }
        }
        xhr.open("delete", "http://localhost/doAjaxDelete?id=2", true);
        xhr.send(null);
    }

    function doAjaxUpdate() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("result").innerHTML = xhr.responseText;
            }
        }
        xhr.open("PUT", "http://localhost/doAjaxUpdate?id=2&name=电视&remark=高清TV", true);
        xhr.send();
    }

</script>

</body>
</html>